import { LitElement, html, css } from 'lit';
import { customElement, property, state } from 'lit/decorators.js';

/**
 * Pagination分页组件
 * @element zss-pagination
 */
@customElement('zss-pagination')
export class ZssPagination extends LitElement {
  static styles = css`
    :host {
      display: inline-block;
    }

    .pagination {
      display: flex;
      align-items: center;
      gap: 8px;
      font-size: var(--zss-font-size-base);
    }

    .pagination__item {
      display: flex;
      align-items: center;
      justify-content: center;
      min-width: 32px;
      height: 32px;
      padding: 0 8px;
      border: 1px solid var(--zss-border-color);
      border-radius: var(--zss-border-radius-base);
      background-color: var(--zss-bg-color);
      color: var(--zss-text-color-regular);
      cursor: pointer;
      user-select: none;
      transition: all 0.2s;
    }

    .pagination__item:hover {
      color: var(--zss-color-primary);
      border-color: var(--zss-color-primary);
    }

    .pagination__item.active {
      background-color: var(--zss-color-primary);
      border-color: var(--zss-color-primary);
      color: var(--zss-color-white);
    }

    .pagination__item.disabled {
      color: var(--zss-text-color-disabled);
      border-color: var(--zss-border-color-light);
      background-color: var(--zss-fill-color-light);
      cursor: not-allowed;
    }

    .pagination__item.disabled:hover {
      color: var(--zss-text-color-disabled);
      border-color: var(--zss-border-color-light);
    }

    .pagination__jump {
      display: flex;
      align-items: center;
      gap: 8px;
      margin-left: 16px;
    }

    .pagination__jump-input {
      width: 60px;
      border: 1px solid var(--zss-border-color);
      border-radius: var(--zss-border-radius-base);
      padding: 4px 8px;
      font-size: var(--zss-font-size-small);
      text-align: center;
    }

    .pagination__jump-input:focus {
      border-color: var(--zss-color-primary);
      outline: none;
    }

    .pagination__total {
      margin-left: 16px;
      color: var(--zss-text-color-secondary);
      font-size: var(--zss-font-size-small);
    }

    .pagination__sizes {
      margin-left: 16px;
    }

    .pagination__sizes-select {
      border: 1px solid var(--zss-border-color);
      border-radius: var(--zss-border-radius-base);
      padding: 4px 8px;
      font-size: var(--zss-font-size-small);
      background-color: var(--zss-bg-color);
    }

    .pagination__ellipsis {
      display: flex;
      align-items: center;
      justify-content: center;
      min-width: 32px;
      height: 32px;
      color: var(--zss-text-color-secondary);
    }
  `;

  /**
   * 总条目数
   * @attr total
   */
  @property({ type: Number })
  total = 0;

  /**
   * 每页显示条目个数
   * @attr page-size
   */
  @property({ type: Number })
  pageSize = 10;

  /**
   * 当前页数
   * @attr current-page
   */
  @property({ type: Number })
  currentPage = 1;

  /**
   * 页码按钮的数量
   * @attr pager-count
   */
  @property({ type: Number })
  pagerCount = 7;

  /**
   * 是否显示总条目数
   * @attr show-total
   */
  @property({ type: Boolean })
  showTotal = false;

  /**
   * 是否显示页码选择器
   * @attr show-sizes
   */
  @property({ type: Boolean })
  showSizes = false;

  /**
   * 每页显示个数选择器的选项设置
   * @attr page-sizes
   */
  @property({ type: Array })
  pageSizes = [10, 20, 30, 40, 50, 100];

  /**
   * 是否显示跳转
   * @attr show-jump
   */
  @property({ type: Boolean })
  showJump = false;

  /**
   * 是否禁用
   * @attr disabled
   */
  @property({ type: Boolean })
  disabled = false;

  @state()
  private jumpPage = '';

  private get totalPages() {
    return Math.ceil(this.total / this.pageSize);
  }

  private get pageNumbers() {
    const current = this.currentPage;
    const pageCount = this.pagerCount;
    const totalPages = this.totalPages;
    
    if (totalPages <= pageCount) {
      return Array.from({ length: totalPages }, (_, i) => i + 1);
    }
    
    const half = Math.floor(pageCount / 2);
    let start = current - half;
    let end = current + half;
    
    if (start < 1) {
      start = 1;
      end = pageCount;
    }
    
    if (end > totalPages) {
      end = totalPages;
      start = totalPages - pageCount + 1;
    }
    
    const pages = [];
    
    if (start > 1) {
      pages.push(1);
      if (start > 2) {
        pages.push('...');
      }
    }
    
    for (let i = start; i <= end; i++) {
      pages.push(i);
    }
    
    if (end < totalPages) {
      if (end < totalPages - 1) {
        pages.push('...');
      }
      pages.push(totalPages);
    }
    
    return pages;
  }

  private handlePageChange(page: number) {
    if (this.disabled || page < 1 || page > this.totalPages || page === this.currentPage) {
      return;
    }
    
    this.currentPage = page;
    this.dispatchEvent(new CustomEvent('current-change', { 
      detail: { currentPage: page } 
    }));
  }

  private handleSizeChange(e: Event) {
    const select = e.target as HTMLSelectElement;
    const newSize = parseInt(select.value);
    
    if (newSize !== this.pageSize) {
      this.pageSize = newSize;
      this.currentPage = 1;
      
      this.dispatchEvent(new CustomEvent('size-change', { 
        detail: { pageSize: newSize, currentPage: 1 } 
      }));
    }
  }

  private handleJump() {
    const page = parseInt(this.jumpPage);
    if (page >= 1 && page <= this.totalPages) {
      this.handlePageChange(page);
      this.jumpPage = '';
    }
  }

  private handleJumpInput(e: KeyboardEvent) {
    if (e.key === 'Enter') {
      this.handleJump();
    }
  }

  render() {
    const isFirstPage = this.currentPage === 1;
    const isLastPage = this.currentPage === this.totalPages;

    return html`
      <div class="pagination">
        <!-- 上一页 -->
        <div 
          class="pagination__item ${isFirstPage || this.disabled ? 'disabled' : ''}"
          @click=${() => this.handlePageChange(this.currentPage - 1)}
        >
          上一页
        </div>

        <!-- 页码 -->
        ${this.pageNumbers.map(page => {
          if (page === '...') {
            return html`<div class="pagination__ellipsis">...</div>`;
          }
          
          const pageNum = page as number;
          return html`
            <div 
              class="pagination__item 
                ${pageNum === this.currentPage ? 'active' : ''}
                ${this.disabled ? 'disabled' : ''}"
              @click=${() => this.handlePageChange(pageNum)}
            >
              ${pageNum}
            </div>
          `;
        })}

        <!-- 下一页 -->
        <div 
          class="pagination__item ${isLastPage || this.disabled ? 'disabled' : ''}"
          @click=${() => this.handlePageChange(this.currentPage + 1)}
        >
          下一页
        </div>

        <!-- 总条目数 -->
        ${this.showTotal ? html`
          <div class="pagination__total">
            共 ${this.total} 条
          </div>
        ` : ''}

        <!-- 每页显示个数选择器 -->
        ${this.showSizes ? html`
          <div class="pagination__sizes">
            <select 
              class="pagination__sizes-select"
              ?disabled=${this.disabled}
              @change=${this.handleSizeChange}
            >
              ${this.pageSizes.map(size => html`
                <option value=${size} ?selected=${size === this.pageSize}>
                  ${size} 条/页
                </option>
              `)}
            </select>
          </div>
        ` : ''}

        <!-- 跳转 -->
        ${this.showJump ? html`
          <div class="pagination__jump">
            <span>跳转</span>
            <input
              class="pagination__jump-input"
              type="number"
              min="1"
              max=${this.totalPages}
              .value=${this.jumpPage}
              @input=${(e: Event) => this.jumpPage = (e.target as HTMLInputElement).value}
              @keydown=${this.handleJumpInput}
              ?disabled=${this.disabled}
            />
            <span>页</span>
          </div>
        ` : ''}
      </div>
    `;
  }
}

declare global {
  interface HTMLElementTagNameMap {
    'zss-pagination': ZssPagination;
  }
}